/***************************************************************************
 * Copyright 2012-2013 TXT e-solutions SpA
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * This work was performed within the IoT_at_Work Project
 * and partially funded by the European Commission's
 * 7th Framework Programme under the contract ICT-257367.
 *
 * Authors:
 *      Salvatore Piccione (TXT e-solutions SpA)
 *
 * Contributors:
 *        Domenico Rotondi (TXT e-solutions SpA)
 **************************************************************************/
package it.txt.ens.authorisationService.osgi;

import it.txt.access.capability.pdp.client.PDPClientConfiguration;
import it.txt.access.capability.pdp.client.PDPClientFactory;
import it.txt.ens.authorisationService.amqp.ManagedBroker;
import it.txt.ens.authorisationService.amqp.ManagedNamespace;
import it.txt.ens.authorisationService.amqp.ManagedVirtualHost;
import it.txt.ens.authorisationService.gui.standalone.ENSAuthorisationServiceGUI;
import it.txt.ens.authorisationService.util.AccessRequestListener;
import it.txt.ens.authorisationService.util.ConfigurationParser;
import it.txt.ens.authorisationService.util.PropertiesKeys;
import it.txt.ens.core.ENSAuthzServiceConnectionParameters;
import it.txt.ens.core.KeystoreParameters;
import it.txt.ens.core.X509CertificateRetrievalParameters;
import it.txt.ens.core.factory.ENSAuthzServiceConnectionParametersFactory;
import it.txt.ens.core.factory.ENSResourceFactory;
import it.txt.ens.core.factory.KeystoreParametersFactory;
import it.txt.ens.core.factory.X509CertificateRetrievalParametersFactory;
import it.txt.ens.core.util.parser.KeystoreParametersMapParser;
import it.txt.ens.core.util.parser.ParseException;
import it.txt.ens.core.util.parser.X509CertificateRetrievalParametersMapParser;
import it.txt.ens.namespace.NamespaceInquirerConfiguration;
import it.txt.ens.namespace.NamespaceInquirerFactory;
import it.txt.ens.schema.request.factory.ENSAuthorisationRequestFactory;
import it.txt.ens.schema.response.factory.ENSAuthorisationResponseFactory;
import it.txt.rabbitmq.management.rest.factory.PermissionServiceFactory;
import it.txt.rabbitmq.management.rest.factory.QueueServiceFactory;
import it.txt.rabbitmq.management.rest.factory.UserServiceFactory;
import it.txt.rabbitmq.management.rest.services.QueueService;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.concurrent.ConcurrentMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.SynchronousBundleListener;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;

/**
 * @author Salvatore Piccione (TXT e-solutions SpA - salvatore.piccione AT txtgroup.com)
 * @author Domenico Rotondi (TXT e-solutions SpA - domenico.rotondi AT txtgroup.com)
 *
 */
public class ENSAuthorisationServiceMS implements ManagedService,SynchronousBundleListener {
    
    private AccessRequestListener ensAuthzService;
    
    public static final String SERVICE_PID = "ens-authorisation-service";
    private static final int PROPERTY_COUNT = 4;
    private static final int SERVICE_REF_COUNT = 8;
    private List<ServiceReference<?>> references = new ArrayList<ServiceReference<?>>(SERVICE_REF_COUNT);
    private static final Logger LOGGER = Logger.getLogger(ENSAuthorisationServiceMS.class.getName());
    private static final ResourceBundle MESSAGES = ResourceBundle.getBundle(
            "message-bundles/" + ENSAuthorisationServiceMS.class.getSimpleName(), Locale.ROOT);
    private BundleContext context;
//    private ENSAuthzServiceConnectionParameters ensAuthzServiceConnParams;
    private ENSAuthorisationServiceGUI gui;
    private String bundleName;
    
    ENSAuthorisationServiceMS (BundleContext context) {
        this.context = context;
        this.bundleName = context.getBundle().getSymbolicName();
    }
    
    /* (non-Javadoc)
     * @see org.osgi.service.cm.ManagedService#updated(java.util.Dictionary)
     */
    @Override
    public void updated(Dictionary<String, ?> properties)
            throws ConfigurationException {
        if (properties == null) {
            //stop the service
            if (ensAuthzService != null) {
                stop();
            }
            //do nothing if both properties and service are null
        } else {
            //create and start the service
            if (ensAuthzService == null) {
                start(properties);
            } else {
                //stop and restart the service with the new configuration
                if (LOGGER.isLoggable(Level.FINER))
                    LOGGER.log(Level.FINER, MESSAGES.getString("restartingService"));
                stop();
                start(properties);
            }
        }
    }
    
    private void start (Dictionary<String, ?> properties) throws ConfigurationException{
        if (LOGGER.isLoggable(Level.FINER))
            LOGGER.log(Level.FINER, MESSAGES.getString("startingService"));
        List<String> missingProperties = new ArrayList<String>(PROPERTY_COUNT);
        String configFilePath = null;
        boolean guiIsEnabled = false;
        
        Object propertyObj = properties.get(PropertiesKeys.CONFIGURATION_FILE_PATH_ATTRIBUTE);
        if (propertyObj == null)
            missingProperties.add(PropertiesKeys.CONFIGURATION_FILE_PATH_ATTRIBUTE);
        else
            configFilePath = (String) propertyObj;
        propertyObj = properties.get(PropertiesKeys.NAMESPACE_CHECK_FLAG);
        if (propertyObj == null)
            System.setProperty(PropertiesKeys.NAMESPACE_CHECK_FLAG, 
                "false");
        else
            System.setProperty(PropertiesKeys.NAMESPACE_CHECK_FLAG, 
                    Boolean.toString((Boolean) propertyObj));
        //uncomment to enable thread pooling
        int threadPoolSize = -1;
        propertyObj = properties.get(PropertiesKeys.THREAD_POOL_SIZE_ATTRIBUTE);
        if (propertyObj == null)
            missingProperties.add(PropertiesKeys.THREAD_POOL_SIZE_ATTRIBUTE);
        else
            threadPoolSize = (Integer) propertyObj;
        //uncomment to enable the gui management
//        propertyObj = properties.get(PropertiesKeys.ENS_GUI_ATTRIBUTE);
//        if (propertyObj == null)
//            missingProperties.add(PropertiesKeys.ENS_GUI_ATTRIBUTE);
//        else
//            guiIsEnabled = (Boolean) propertyObj;
        
//        propertyObj = properties.get(PropertiesKeys.QUEUE_NAME_FORMAT);
//        if (propertyObj == null)
//            missingProperties.add(PropertiesKeys.QUEUE_NAME_FORMAT);
//        else
//            operativeQueueNameFormat = (String) propertyObj;
        if (missingProperties.size() > 0) {
            String missingPropertiesSTR = this.buildList(missingProperties);
            LOGGER.log(Level.SEVERE, MessageFormat.format(MESSAGES.getString("missingProperties"), 
                    missingProperties.size()),missingPropertiesSTR);
            throw new ConfigurationException(missingPropertiesSTR, "Missing");
        }
        Properties config = null;
        try {
            config = this.loadProperties(configFilePath);
        } catch (IOException e) {
            String message = MessageFormat.format(MESSAGES.getString("configFileReadingError"), configFilePath);
            LOGGER.log(Level.SEVERE, message, e);
            throw new ConfigurationException(PropertiesKeys.CONFIGURATION_FILE_PATH_ATTRIBUTE, message);
        }
        
        ServiceReference<ENSAuthzServiceConnectionParametersFactory> connParamsSFRef = 
            context.getServiceReference(ENSAuthzServiceConnectionParametersFactory.class);
        if (connParamsSFRef == null) {
            String reason = MessageFormat.format(MESSAGES.getString("missingOSGiService"), 
                    ENSAuthzServiceConnectionParametersFactory.class.getName());
            LOGGER.severe(reason);
            throw new ConfigurationException(null, reason);
        }
        ENSAuthzServiceConnectionParametersFactory connParamsSF =
            context.getService(connParamsSFRef);
        references.add(connParamsSFRef); 
        
        ConfigurationParser parser = new ConfigurationParser(config, connParamsSF);
        
        ConcurrentMap<String, ManagedNamespace> namespaceMap = parser.getNamespaceMap();
        
        ConcurrentMap<String, ManagedBroker> brokerMap = parser.getBrokerMap();
        
        ConcurrentMap<String, ManagedVirtualHost> virtualHostMap = parser.getVirtualHostMap();
        
        ServiceReference<PDPClientFactory> pdpClientFactorySR = context.getServiceReference(PDPClientFactory.class);
        if (pdpClientFactorySR ==  null) {
            String reason = MessageFormat.format(MESSAGES.getString("missingOSGiService"), 
                    PDPClientFactory.class.getName());
            LOGGER.severe(reason);
            throw new ConfigurationException(null, reason);
        }
        PDPClientFactory pdpClientFactory = context.getService(pdpClientFactorySR);
        references.add(pdpClientFactorySR); 
        PDPClientConfiguration pdpClientConfiguration = pdpClientFactory.createConfiguration(config);
        
        //retrieve namespace inquirer factory
        ServiceReference<NamespaceInquirerFactory> namespaceInquirerFactorySR = 
            context.getServiceReference(NamespaceInquirerFactory.class);
        if (namespaceInquirerFactorySR == null) {
            String reason = MessageFormat.format(MESSAGES.getString("missingOSGiService"), 
                    NamespaceInquirerFactory.class.getName());
            LOGGER.severe(reason);
            throw new ConfigurationException(null, reason);
        }
        NamespaceInquirerFactory namespaceInquirerFactory = context.getService(namespaceInquirerFactorySR);
        references.add(namespaceInquirerFactorySR); 
        NamespaceInquirerConfiguration namespaceInquirerConfig = namespaceInquirerFactory.createConfiguration(config);
        
        ServiceReference<UserServiceFactory> userMgmtSF_SR = context.getServiceReference(UserServiceFactory.class);
        if (userMgmtSF_SR == null) {
            String reason = MessageFormat.format(MESSAGES.getString("missingOSGiService"), 
                    UserServiceFactory.class.getName());
            LOGGER.severe(reason);
            throw new ConfigurationException(null, reason);
        }
        UserServiceFactory userMgmtSF = context.getService(userMgmtSF_SR);
        references.add(userMgmtSF_SR); 
        
        ServiceReference<PermissionServiceFactory> permissionMgmtSF_SR =
                context.getServiceReference(PermissionServiceFactory.class);
        if (permissionMgmtSF_SR == null) {
            String reason = MessageFormat.format(MESSAGES.getString("missingOSGiService"), 
                    PermissionServiceFactory.class.getName());
            LOGGER.severe(reason);
            throw new ConfigurationException(null, reason);
        }
        PermissionServiceFactory permissionMgmtSF = context.getService(permissionMgmtSF_SR);
        references.add(permissionMgmtSF_SR); 
        
        ServiceReference<QueueServiceFactory> queueMgmtSF_SR =
                context.getServiceReference(QueueServiceFactory.class);
        if (queueMgmtSF_SR == null) {
            String reason = MessageFormat.format(MESSAGES.getString("missingOSGiService"), 
                    QueueServiceFactory.class.getName());
            LOGGER.severe(reason);
            throw new ConfigurationException(null, reason);
        }
        QueueServiceFactory queueMgmtSF = context.getService(queueMgmtSF_SR);
        ENSAuthzServiceConnectionParameters connParams = parser.getEnsAuthzServiceConnParams();
        QueueService queueMgmt = queueMgmtSF.create(
                connParams.getBrokerHost(), connParams.getManagementPort(),
                //I can do this because the ENS Authorisation Service account has full control
                //also on the Access Request Broker
                connParams.getSubjectID(), connParams.getAccessToken());
        context.ungetService(queueMgmtSF_SR);
        
        ServiceReference<ENSAuthorisationResponseFactory> responseFactorySR = 
            context.getServiceReference(ENSAuthorisationResponseFactory.class);
        if (responseFactorySR == null) {
            String reason = MessageFormat.format(MESSAGES.getString("missingOSGiService"), 
                    ENSAuthorisationResponseFactory.class.getName());
            LOGGER.severe(reason);
            throw new ConfigurationException(null, reason);
        }
        ENSAuthorisationResponseFactory responseFactory = context.getService(responseFactorySR);
        references.add(responseFactorySR);
        
        ServiceReference<ENSAuthorisationRequestFactory> requestFactorySR =
            context.getServiceReference(ENSAuthorisationRequestFactory.class);
        if (requestFactorySR == null) {
            String reason = MessageFormat.format(MESSAGES.getString("missingOSGiService"), 
                    ENSAuthorisationResponseFactory.class.getName());
            LOGGER.severe(reason);
            throw new ConfigurationException(null, reason);
        }
        ENSAuthorisationRequestFactory requestFactory = context.getService(requestFactorySR);
        references.add(requestFactorySR);
        
        ServiceReference<KeystoreParametersFactory> keystoreParamsFactorySR =
                context.getServiceReference(KeystoreParametersFactory.class);
        if (keystoreParamsFactorySR == null) {
            String reason = MessageFormat.format(MESSAGES.getString("missingOSGiService"), 
                    KeystoreParametersFactory.class.getName());
            LOGGER.severe(reason);
            throw new ConfigurationException(null, reason);
        }
        KeystoreParametersFactory keystoreParamsFactory = context.getService(keystoreParamsFactorySR);
        KeystoreParameters keystoreParams;
        try {
            keystoreParams = KeystoreParametersMapParser.parse(keystoreParamsFactory, config);
        } catch (IllegalArgumentException e) {
            String reason = MESSAGES.getString("keystoreParamsParsingError");
            LOGGER.log(Level.SEVERE, reason, e);
            throw new ConfigurationException(null, reason , e);
        } catch (ParseException e) {
            String reason = MESSAGES.getString("keystoreParamsParsingError");
            LOGGER.log(Level.SEVERE, reason, e);
            throw new ConfigurationException(null, reason , e);
        } finally {
            context.ungetService(keystoreParamsFactorySR);
        }
        
        ServiceReference<X509CertificateRetrievalParametersFactory> certParamsFactorySR =
                context.getServiceReference(X509CertificateRetrievalParametersFactory.class);
        if (certParamsFactorySR == null) {
            String reason = MessageFormat.format(MESSAGES.getString("missingOSGiService"), 
                    X509CertificateRetrievalParametersFactory.class.getName());
            LOGGER.severe(reason);
            throw new ConfigurationException(null, reason);
        }
        X509CertificateRetrievalParametersFactory certParamsFactory = context.getService(certParamsFactorySR);
        X509CertificateRetrievalParameters certParams;
        try {
            certParams = X509CertificateRetrievalParametersMapParser.parse(certParamsFactory, config);
        } catch (IllegalArgumentException e) {
            String reason = MESSAGES.getString("keystoreParamsParsingError");
            LOGGER.log(Level.SEVERE, reason, e);
            throw new ConfigurationException(null, reason , e);
        } catch (ParseException e) {
            String reason = MESSAGES.getString("keystoreParamsParsingError");
            LOGGER.log(Level.SEVERE, reason, e);
            throw new ConfigurationException(null, reason , e);
        } finally {
            context.ungetService(certParamsFactorySR);
        }
        
        ServiceReference<ENSResourceFactory> resourceFactorySR =
                context.getServiceReference(ENSResourceFactory.class);
        if (resourceFactorySR == null) {
            String reason = MessageFormat.format(MESSAGES.getString("missingOSGiService"), 
                    ENSResourceFactory.class.getName());
            LOGGER.severe(reason);
            throw new ConfigurationException(null, reason);
        }
        ENSResourceFactory resourceFactory = context.getService(resourceFactorySR);
        references.add(requestFactorySR);
        
//        LOGGER.info(connParams.getSubjectID() + " " + connParams.getAccessToken());
        ensAuthzService = new AccessRequestListener(connParams, pdpClientFactory, 
            pdpClientConfiguration, namespaceInquirerFactory, namespaceInquirerConfig,
            userMgmtSF, permissionMgmtSF, queueMgmt,
            responseFactory, requestFactory, keystoreParams, certParams, resourceFactory, virtualHostMap,
            namespaceMap, brokerMap, threadPoolSize);
        ensAuthzService.start();
        //check if we have to start the GUI
        
        if (guiIsEnabled) {
            gui = new ENSAuthorisationServiceGUI(ensAuthzService);
            gui.setVisible(true);
        }
        if (LOGGER.isLoggable(Level.INFO))
            LOGGER.log(Level.INFO, MESSAGES.getString("serviceStarted"));
    }
    
    private String buildList (List<String> elements) {
        StringBuilder list = new StringBuilder();
        for (int i = 0; i < elements.size(); i++) {
            if (i > 0)
                list.append(", ");
            list.append(elements.get(i));
        }
        return list.toString();
    }
    
    private Properties loadProperties (String configFilePath) throws IOException {
        File file = new File(configFilePath);
        FileInputStream stream = new FileInputStream(file);
        Properties p = new Properties();
        try {
            p.load(stream);
        } finally {
            if (stream != null)
                stream.close();
        }
        return p;
    }
//    
//    private ConcurrentMap<String,ManagedNamespace> parseNamespaceJSONArray (String jsonArray) {
//        Gson gson = new Gson();
//        JsonParser parser = new JsonParser();
//        JsonArray rawNamespaceList = parser.parse(jsonArray).getAsJsonArray();
//        ConcurrentMap<String,ManagedNamespace> namespaceMap = 
//                new ConcurrentHashMap<String, ManagedNamespace>(rawNamespaceList.size());
//        ManagedNamespace namespace;
//        for (int i = 0; i < rawNamespaceList.size(); i++) {
//            namespace = gson.fromJson(rawNamespaceList.get(i), ManagedNamespace.class);
//            namespaceMap.put(namespace.getNamespaceName(), namespace);
//        }
//        return namespaceMap;
//    }
//
//    private ConcurrentMap<String,ManagedBroker> parseBrokerJSONArray (String jsonArray) {
//        Gson gson = new Gson();
//        JsonParser parser = new JsonParser();
//        JsonArray rawBrokerList = parser.parse(jsonArray).getAsJsonArray();
//        ConcurrentMap<String,ManagedBroker> brokerMap = 
//                new ConcurrentHashMap<String, ManagedBroker>(rawBrokerList.size());
//        ManagedBroker broker;
//        for (int i = 0; i < rawBrokerList.size(); i++) {
//            broker = gson.fromJson(rawBrokerList.get(i), ManagedBroker.class);
//            brokerMap.put(broker.getBrokerName(), broker);
//        }
//        return brokerMap;
//    }
//    
//    private ConcurrentMap<String,ManagedVirtualHost> parseVirtualHostJSONArray (String jsonArray,
//            ENSAuthzServiceConnectionParametersFactory factory, Map<String,ManagedBroker> brokerMap) {
//        Gson gson = new Gson();
//        JsonParser parser = new JsonParser();
//        JsonArray rawVirtualHostList = parser.parse(jsonArray).getAsJsonArray();
//        ConcurrentMap<String,ManagedVirtualHost> virtualHostMap = 
//                new ConcurrentHashMap<String, ManagedVirtualHost>(rawVirtualHostList.size());
//        ManagedVirtualHost vHost;
//        for (int i = 0; i < rawVirtualHostList.size(); i++) {
//            vHost = gson.fromJson(rawVirtualHostList.get(i), ManagedVirtualHost.class);
//            if (vHost.getVirtualHostType() == Type.Access) {
//                ManagedBroker authzServiceBroker = brokerMap.get(vHost.getHostingBrokerName());
//                this.ensAuthzServiceConnParams = factory.create(
//                    vHost.getBrokerUsername(), vHost.getBrokerPassword(),
//                    authzServiceBroker.getIpAddress(), authzServiceBroker.getTcpPortNumber(),
//                    vHost.getVirtualHostName(), vHost.getENSAuthenticationServiceQueueName(), false);
//            } else            
//                virtualHostMap.put(vHost.getVirtualHostName(), vHost);
//        }
//        return virtualHostMap;
//    }
//    
    public void stop () {
        if (LOGGER.isLoggable(Level.FINER))
            LOGGER.log(Level.FINER, MESSAGES.getString("stoppingService"));
        ensAuthzService.stop();
        ensAuthzService = null;
        if (gui != null) {
            //TODO destroy the GUI
            gui = null;
        }
        for (ServiceReference<?> ref: references)
            context.ungetService(ref);
        
        if (LOGGER.isLoggable(Level.INFO))
            LOGGER.log(Level.INFO, MESSAGES.getString("serviceStopped"));
    }


    /* (non-Javadoc)
     * @see org.osgi.framework.BundleListener#bundleChanged(org.osgi.framework.BundleEvent)
     */
    @Override
    public void bundleChanged(BundleEvent event) {
        if (bundleName.equals(event.getBundle().getSymbolicName()) && (event.getType() == 
                BundleEvent.STOPPING || event.getType() == BundleEvent.UNINSTALLED) &&
                ensAuthzService != null) {
            stop();
        }
        
    }
}
